/*
 * @Author: your name
 * @Date: 2021-10-29 15:44:44
 * @LastEditTime: 2021-11-04 14:48:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \macc.admin.vue\src\utils\tools.js
 */

//获取父页面的头部和左侧菜单的宽高，然后设置子页面的
import introJS from 'intro.js';
import 'intro.js/introjs.css';
import Vue from 'vue';
import { i18nRender } from '@/locales';

const setFrameLayout = function (store) {
  if (self == parent) return; //页面没有被内嵌在
  getParentLayout(store);
  if (!window.onresize) {
    window.onresize = () => {
      getParentLayout(store);
    };
  }
};

const getParentLayout = function (store) {
  const topLayoutHeight = parent.document.getElementById('navbarBackground')
    ? parent.document.getElementById('navbarBackground').offsetHeight
    : null;
  const leftLayoutWidth = parent.document.getElementById('sidemenu')
    ? parent.document.getElementById('sidemenu').offsetWidth
    : null;
  store.commit('Layout/SET_LAYOUT_DISTANCE', {
    topLayoutHeight,
    leftLayoutWidth,
  });
};

//url参数转对象
const parseQueryString = function (url) {
  url = url == null ? window.location.href : url;
  if (url.indexOf('?') == -1) {
    return {};
  }
  let search;
  search = url.substring(url.lastIndexOf('?') + 1);
  const param =
    search && search.indexOf('=') > -1
      ? JSON.parse(
          '{"' +
            decodeURIComponent(search)
              .replace(/"/g, '\\"')
              .replace(/&/g, '","')
              .replace(/=/g, '":"') +
            '"}'
        )
      : {};
  return param;
};

//去除前后空格
const toTrim = function (values) {
  return values.replace(/(^\s*)|(\s*$)/g, '');
};

const getParentPageGroupId = function (store) {
  if (self != parent) {
    const groupId = parent.groupBar.getCurrentGroup().groupId;
    store.commit('Group/SET_GROUPID', groupId);
  }
};

//分组数格式化为map
const groupTree2Map = function (groups, parentGroup, groupMap) {
  const group = Object.assign(
    { parentGroupId: (parentGroup && parentGroup.groupId) || null },
    groups
  );
  groupMap[groups.groupId] = group;
  if (groups.subGroups && groups.subGroups.length > 0) {
    for (let i = 0; i < groups.subGroups.length; i++) {
      groupTree2Map(groups.subGroups[i], groups, groupMap);
    }
  }
};

const totalProject = function (groupMap) {
  const projectList = Object.values(groupMap).filter(
    (item) => item.type === 'BUILDING'
  );
  return projectList.length;
};

const sleep = function (time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};

//判断数据中是否存在重复项
const isRepeat = function (arr) {
  const hash = {};
  for (let i in arr) {
    let ip = toTrim(arr[i]);
    if (hash[ip]) {
      return true;
    }
    // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
    hash[ip] = true;
  }
  return false;
};
/**
 * 将走势图中断裂的部分进行补点操作 1、arr为null或者空数组，原样返回 2、填充节点仅放入时间字段，无其他数据字段填充
 *
 * @param arr
 *            数据数组
 * @param start
 *            时间区间开始时间戳
 * @param end
 *            时间区间结束时间戳
 * @param timefield
 *            数据时间字段
 * @param dataIntervalSeconds
 *            数据节点之间的时间间隔（秒）
 * @param maxMissingIntervalSeconds
 *            判定数据断裂的时间间隔（秒）
 * @return
 */
const fillTimeLineData = function (
  arr,
  start,
  end,
  timefield,
  dataIntervalSeconds,
  maxMissingIntervalSeconds
) {
  if (Array.isArray(arr) && arr.length > 0) {
    //判断数组中得数据是否都包含事件数据字段
    for (let i = 0; i < arr.length; i++) {
      if (
        !(timefield && Object.prototype.hasOwnProperty.call(arr[i], timefield))
      ) {
        return arr;
      }
    }
    const result = [];
    const maxMissIntervalMills = maxMissingIntervalSeconds * 1000;
    const dataIntervalMills = dataIntervalSeconds * 1000;
    let index = 0;
    let current = arr[index][timefield];
    while (start < end) {
      if (index < arr.length && current - start < maxMissIntervalMills) {
        result.push(arr[index++]);
        start = current;
        // if (index < arr.size()) {
        //   current = arr[index][timefield];
        // }
        if (index < arr.length) {
          current = arr[index][timefield];
        }
      } else {
        start = start + dataIntervalMills;
        let obj = {};
        obj[timefield] = start;
        result.push(obj);
      }
    }
    return result;
  } else {
    return arr;
  }
};

//分钟转换天，小时，分
const formatterLeaseTime = function (leaseTime) {
  var time = parseInt(leaseTime);
  var day = Math.floor(time / 60 / 24);
  var hour = Math.floor((time - day * 60 * 24) / 60);
  var minute = time - day * 60 * 24 - hour * 60;
  return { day: day, hour: hour, minute: minute };
};

/**
 * @desc 计算字符串字节长度
 * @param {String} str 需要计算的字符串
 * @return {Number}
 */
const getByteLength = (str = '') => {
  if (str && typeof str == 'string') {
    try {
      let len = 0;
      for (let i = 0, l = str.length; i < l; i++) {
        len += str.charCodeAt(i) <= 128 ? 1 : 2;
      }
      return len;
    } catch (error) {
      throw new Error(error);
    }
  } else {
    return 0;
  }
};

const introTool = function (params, delay = 10000) {
  const { setOptions, oncomplete, onexit, onafterchange } = params;
  const { steps } = setOptions;
  // 超时检测函数
  const timeOut = (delay) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(i18nRender('portdiagnose.timeout'));
      }, delay);
    });
  };

  const waitDom = () => {
    return new Promise((resolve, reject) => {
      let t = 0;
      const timer = setInterval(() => {
        if (t < delay) {
          t = t + 500;
        } else {
          clearInterval(timer);
        }
        const complete = allDomIsRender();
        console.log('complete', complete);
        if (complete) {
          timer && clearInterval(timer);
          resolve();
        }
      }, 500);
    });
  };

  const allDomIsRender = () => {
    console.log('steps', steps);
    return steps.every((item) => {
      const { element } = item;
      let dom;
      const eleStr = element.substr(1);
      if (element.startsWith('.')) {
        dom = document.getElementsByClassName(eleStr)[0];
      } else if (element.startsWith('#')) {
        console.log('eleStr', eleStr, document.getElementById(eleStr));
        if (document.getElementById(eleStr)) {
          dom = document.getElementById(eleStr);
        }
      }
      return dom ? true : false;
    });
  };

  return new Promise((resolve, reject) => {
    Promise.race([waitDom(), timeOut(delay)])
      .then(() => {
        Vue.nextTick(() => {
          introJS()
            .setOptions({
              ...setOptions,
            })
            .oncomplete(() => {
              //点击跳过引导
              if (self != top) {
                top.$('body').removeClass('subWebModal');
              }
              oncomplete && typeof oncomplete == 'function' && oncomplete();
            })
            .onafterchange(() => {
              //下一步切换
              onafterchange &&
                typeof onafterchange == 'function' &&
                onafterchange();
            })
            .onexit(() => {
              //引导结束
              if (self != top) {
                top.$('body').removeClass('subWebModal');
              }
              onexit && typeof onexit == 'function' && onexit();
            })
            .start();
          if (self != top) {
            top.$('body').addClass('subWebModal');
          }
          resolve();
        });
      })
      .catch((err) => {
        console.log(err, 'ohhhhhhhhh');
        reject(err);
      });
  });
};

//kbps 转 Mbpas
const kbpsTombps = function (val, fixed) {
  return (parseFloat(val) / 1000).toFixed(fixed ?? 3);
};

const mbpsTokbps = function (val, fixed) {
  return (val * 1000).toFixed(fixed ?? 0);
};

const guid = function () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};
export {
  setFrameLayout,
  parseQueryString,
  getParentPageGroupId,
  groupTree2Map,
  totalProject,
  toTrim,
  fillTimeLineData,
  isRepeat,
  sleep,
  formatterLeaseTime,
  getByteLength,
  introTool,
  kbpsTombps,
  mbpsTokbps,
  guid,
};
